#include "tsv_parser.hh"

#include <fstream>
#include <sstream>
#include <exception>

bool TsvParser::loadFromMemory(const std::string &text) {
    std::istringstream ss(text);
    loadFromStream(ss);
    return true;
}

bool TsvParser::loadFromFile(const std::string &filename) {
    std::ifstream fs;
    fs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    fs.open(filename, std::ios::in);
    if (!fs.is_open()) return false;
    loadFromStream(fs);
    fs.close();
    return true;
}

void TsvParser::loadFromStream(std::istream &is) {
    char line[256 * 256];
    bool firstline = true;
    size_t cols = 0;
    std::vector<std::string> *thisline;
    while (!is.eof()) {
        is.getline(line, 256 * 256);
        std::istringstream ss(line, std::ios::in);
        size_t index = 0;
        if (!firstline) {
            content_.resize(content_.size() + 1);
            thisline = &content_.back();
            thisline->resize(cols);
        }
        while (!ss.eof()) {
            char part[4096];
            ss.getline(part, 4096, '\t');
            if (firstline)
                titles_.push_back(part);
            else {
                (*thisline)[index++] = part;
                if (index >= cols) break;
            }
        }
        if (firstline) {
            cols = titles_.size();
            firstline = false;
        }
    }
}
